package com.sk.cardeal.act;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sk.cardeal.R;
import com.sk.cardeal.act.home.HomeFragment;
import com.sk.cardeal.act.manage.ManageFragment;
import com.sk.cardeal.act.manual.ManualFragment;
import com.sk.cardeal.act.recommend.RecommendFragment;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.dialog.TipDialogFragement;
import com.sk.cardeal.dialog.UpDateDialogFragment;
import com.sk.cardeal.utils.ExampleUtil;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.SnackUtils;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_manual)
    RadioButton rbManual;
    @BindView(R.id.rb_manage)
    RadioButton rbManage;
    @BindView(R.id.rb_recommend)
    RadioButton rbRecommend;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;

    HomeFragment homeFragment;
    ManualFragment manualFragment;
    ManageFragment manageFragment;
    RecommendFragment recommendFragment;

    //设备信息
    String device_info = "";
    String device_ip = "";
    String device_ver = "";
    private static final String BASE_URL = "http://pan-car.oss-cn-hangzhou.aliyuncs.com/version/app-release.apk";
    private String path = "";

    public static boolean isForeground = false;
    private UpDateDialogFragment upDateDialogFragment;

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        path = getSDPath() + "/cardeal/";
        init_fragment();
        initListeners();
        init();
        MainActivityPermissionsDispatcher.startLoadWithPermissionCheck(this);
    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
            return sdDir.toString();
        } else {
            return "";
        }

    }

    private void init_fragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        homeFragment = (HomeFragment) fm.findFragmentByTag(HomeFragment.class.getSimpleName());
        if (homeFragment == null) {
            homeFragment = new HomeFragment();
            ft.add(R.id.fl_content, homeFragment, homeFragment.getClass().getSimpleName());
        }

        manualFragment = (ManualFragment) fm.findFragmentByTag(ManualFragment.class.getSimpleName());
        if (manualFragment == null) {
            manualFragment = new ManualFragment();
            ft.add(R.id.fl_content, manualFragment, manualFragment.getClass().getSimpleName());
        }

        manageFragment = (ManageFragment) fm.findFragmentByTag(ManageFragment.class.getSimpleName());
        if (manageFragment == null) {
            manageFragment = new ManageFragment();
            ft.add(R.id.fl_content, manageFragment, manageFragment.getClass().getSimpleName());
        }

        recommendFragment = (RecommendFragment) fm.findFragmentByTag(RecommendFragment.class.getSimpleName());
        if (recommendFragment == null) {
            recommendFragment = new RecommendFragment();
            ft.add(R.id.fl_content, recommendFragment, recommendFragment.getClass().getSimpleName());
        }

        ft.show(homeFragment);
        ft.hide(manualFragment);
        ft.hide(manageFragment);
        ft.hide(recommendFragment);
        ft.commit();
    }

    private void initListeners() {
        rbHome.setOnCheckedChangeListener(this);
        rbManual.setOnCheckedChangeListener(this);
        rbManage.setOnCheckedChangeListener(this);
        rbRecommend.setOnCheckedChangeListener(this);
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        switch (compoundButton.getId()) {
            case R.id.rb_home:
                if (isChecked) {
                    showHome();
                }
                break;
            case R.id.rb_manual:
                if (isChecked) {
                    showManual();
                }
                break;
            case R.id.rb_manage:
                if (isChecked) {
                    showManage();
                }
                break;
            case R.id.rb_recommend:
                if (isChecked) {
                    showRecommend();
                }
                break;
        }
    }

    private void showHome() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.show(homeFragment);
        ft.hide(manualFragment);
        ft.hide(manageFragment);
        ft.hide(recommendFragment);
        ft.commit();
    }

    private void showManual() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.hide(homeFragment);
        ft.show(manualFragment);
        ft.hide(manageFragment);
        ft.hide(recommendFragment);
        ft.commit();
    }

    private void showManage() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.hide(homeFragment);
        ft.hide(manualFragment);
        ft.show(manageFragment);
        ft.hide(recommendFragment);
        ft.commit();
    }

    private void showRecommend() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.hide(homeFragment);
        ft.hide(manualFragment);
        ft.hide(manageFragment);
        ft.show(recommendFragment);
        ft.commit();
    }


    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    private void setCostomMsg(String msg) {

    }

    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void init() {
        String ss = "1";
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,
                ss));
    }

    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    JPushInterface.setAliasAndTags(getApplicationContext(), null,
                            (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
            }
        }
    };


    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    break;

                case 6002:
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(
                                mHandler.obtainMessage(MSG_SET_ALIAS, alias),
                                1000 * 60);
                    } else {
                    }
                    break;

                default:
            }

        }

    };

    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    break;

                case 6002:
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(
                                mHandler.obtainMessage(MSG_SET_TAGS, tags),
                                1000 * 60);
                    } else {

                    }
                    break;

                default:
            }

        }

    };


    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startLoad() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                getText();
            }
        });

        thread.start();
    }


    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForLoad(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("app需要使用您的读写权限")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForLoad() {
        SnackUtils.showError(mRootView, "您已拒绝了读写权限！");
    }


    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForLoad() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止app使用您的读写权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    private boolean getText() {
        String urlStr = "http://pan-car.oss-cn-hangzhou.aliyuncs.com/version/version.txt";
//        String urlStr = "http://www.xiubom.com/mj/app_update.txt";
        //long a = System.currentTimeMillis();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(60 * 1000);
            conn.setReadTimeout(60 * 1000);
            // 取得inputStream，并进行读取
            InputStream input = conn.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            String line = null;
            final StringBuffer sb = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    JSONObject jsonObject = JSON.parseObject(sb.toString());
                    String updateCode = jsonObject.getString("version_code");
                    String versionCode = MyUtils.getVersionCode(mContext);
                    String updateString = jsonObject.getString("version_info");
                    if (Integer.valueOf(updateCode) > Integer.valueOf(versionCode)) {
                        File dir = new File(path);
                        boolean isCreate = false;
                        if (!dir.exists()) {
                            isCreate = dir.mkdirs();
                        } else {
                            isCreate = true;
                        }
                        if (isCreate) {
                            TipDialogFragement tipDialogFragement = new TipDialogFragement();
                            tipDialogFragement.setMyCallBack(MainActivity.this);
                            tipDialogFragement.setTipContent("为您发现新版本，新版本为您修复了以下问题:"+updateString+"\n\n是否升级？");
                            tipDialogFragement.show(getSupportFragmentManager(), "tip");
                        }
                    }
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }


    @Override
    public void sure() {
        super.sure();
        upDateDialogFragment = new UpDateDialogFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(upDateDialogFragment, this.getClass().getSimpleName());
        ft.commitAllowingStateLoss();//注意这里使用commitAllowingStateLoss()
        downloadFile(BASE_URL, path);
    }

    private void downloadFile(final String url, String path) {
        RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path + "mj_app.apk");
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }

            @Override
            public void onStarted() {
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                int now = (int) (current * 100 / total);
                upDateDialogFragment.setProcess(now + "%");
            }

            @Override
            public void onSuccess(File result) {
                //apk下载完成后，调用系统的安装方法
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
                startActivity(intent);
                android.os.Process.killProcess(android.os.Process.myPid());
                upDateDialogFragment.dismissAllowingStateLoss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                Log.v("onError", ex.toString() + ex.getMessage() + "error");
                Toast.makeText(mContext, ex.toString() + ex.getMessage() + "error", Toast.LENGTH_SHORT).show();
                upDateDialogFragment.dismissAllowingStateLoss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }


}
